package edu.jit.flowers.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import edu.jit.flowers.bean.Address;
import edu.jit.flowers.bean.Flowers;
import edu.jit.flowers.utils.JDBCUtil;

public class AddressDAO {
	//添加收件人地址
    public int addAddress(Address rc) {
   	 int rows=0;
   	 String sql="insert into address values(0,?,?,?)";
   	 
   	 QueryRunner runner=new QueryRunner(JDBCUtil.getDataSource());
   	 try {
			rows=runner.update(sql, rc.getRcName(),rc.getRcAddress(),rc.getRcTel());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
   	 return rows;
   	 
    }
    //根据收件人姓名删除收件人地址
    public int deleteAddressByrcName(String name) {
   	 int rows=0;
   	 String sql="delete from address where rc_name = ?";
   	 QueryRunner runner=new QueryRunner(JDBCUtil.getDataSource());
   	 try {
			rows=runner.update(sql,name);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
   	 return rows;
    }
    //根据收件人Id修改收件人地址
    public int updateAddressById(Address rc) {
   	 int rows=0;
   	 String sql="update address set rc_id=?,rc_name=?,rc_address=?,"
   	 		+ "rc_tel=?where rc_id=?";
   	 QueryRunner runner=new QueryRunner(JDBCUtil.getDataSource());
   	 try {
			rows=runner.update(sql,rc.getRcId(),rc.getRcName(),rc.getRcAddress(),
					rc.getRcTel(),rc.getRcId());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
   	 return rows;
   	 
    }
  //根据收件人姓名修改收件人地址
    public int updateAddressByrcName(Address rc) {
   	 int rows=0;
   	 String sql="update address set rc_id=?,rc_name=?,rc_address=?,"
   	 		+ "rc_tel=?where rc_name=?";
   	 QueryRunner runner=new QueryRunner(JDBCUtil.getDataSource());
   	 try {
			rows=runner.update(sql,rc.getRcId(),rc.getRcName(),rc.getRcAddress(),
					rc.getRcTel(),rc.getRcName());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
   	 return rows;
   	 
    }
    
    //查询所有收件人地址
    public List<Address> selectAll(){
		List<Address> address = new ArrayList<>();
		String sql="select rc_id as rcid,rc_name as rcname,rc_address as rcaddress,rc_tel as rctel from address";
		QueryRunner runner=new QueryRunner(JDBCUtil.getDataSource());
		try {
			address=runner.query(sql, new BeanListHandler<>(Address.class));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       return address;
    }

}
